<template>
    <div class="inputBox">
        <el-form ref="formRef" :rules="rules" :model="roleInfo">
            <el-form-item label-width="80px" label="角色名称" prop="roleName">
                <el-input type="text" v-model="roleInfo.rolename"></el-input>
            </el-form-item>
            <el-form-item label-width="80px" label="角色描述" prop="remark">
                <el-input type="textarea" placeholder="暂无描述" v-model="roleInfo.remark" resize="none" rows="5"
                    show-word-limit maxlength="30"></el-input>
            </el-form-item>
            <el-form-item label-width="80px">
                <el-button type="primary" @click="save(formRef)">保存</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { reqAddRole, reqEditRole } from '@/api/common';
import { roleType } from '@/types/role';
import { FormInstance, FormRules } from 'element-plus';
import { reactive, ref, watch } from 'vue';
const formRef = ref<FormInstance>()

const props = defineProps<{
    roleInfo: roleType | null
}>()
const roleInfo = ref<roleType>({
    rolename: "",
    remark: ""
})
console.log(props.roleInfo);

const emptyInfo = { ...roleInfo.value }
watch(() => props.roleInfo, () => {
    console.log(props);
    if (props.roleInfo) {
        const { rolename, remark } = props.roleInfo
        roleInfo.value = { rolename, remark }
    } else {
        roleInfo.value = emptyInfo
    }

})

const emits = defineEmits(['isShow'])
const emitChange = () => {
    emits('isShow', false)
}
const checkRoleName = (rule: any, value: any, callback: any) => {
    if (value == "") {
        callback(new Error('输入有效角色名'));
    } else {
        callback()
    }
}

const rules = reactive<FormRules>({
    roleName: [{ validator: checkRoleName, trigger: 'blur', required: true }]
})

const save = (formRef: FormInstance | undefined) => {
    if (!formRef) return
    formRef.validate((vaild) => {
        if (vaild) {
            console.log(roleInfo.value);
            if (!props.roleInfo) {
                reqAddRole(roleInfo.value).then(res => {
                    emitChange()
                    roleInfo.value = emptyInfo
                    history.go(0)
                })
            } else {
                roleInfo.value.roleid=props.roleInfo.roleid
                reqEditRole(roleInfo.value).then(res => {
                    emitChange()
                    history.go(0)
                })
            }



        }
    })
}

</script>

<style scoped lang="scss">
.inputBox {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;

    .el-form {
        .el-form-item {
            width: 400px;

            .el-button {
                width: 400px;
            }
        }
    }
}</style>